package com.reborn.mall.api.service.impl;

import com.reborn.mall.api.common.util.JwtTokenUtil;
import com.reborn.mall.api.model.entity.AppUser;
import com.reborn.mall.api.service.AppUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * TODO: Here is description
 *
 * @author wu.yue
 * @since 2020/2/29
 */
@Service
@Slf4j
public class AppUserServiceImpl extends BaseServiceImpl<AppUser> implements AppUserService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public AppUser getUserByUsername(String username) {
        return findOne(new AppUser(username));
    }

    @Override
    public AppUser register(AppUser appUser) {
        appUser.setCreateTime(new Date());
        appUser.setStatus(1);
        AppUser existedUser = findOne(new AppUser(appUser.getUsername()));
        if (existedUser != null) {
            return null;
        }
        // 将密码进行加密操作
        String encodedPassword = passwordEncoder.encode(appUser.getPassword());
        appUser.setPassword(encodedPassword);
        return insert(appUser);
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public Optional<AppUser> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return Optional.ofNullable(getUserByUsername(authentication == null ? null : authentication.getName()));
    }
}
